package com.bjpowernode.crm.settings.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bjpowernode.crm.commons.utils.DateUtils;
import com.bjpowernode.crm.settings.domain.DicValue;
import com.bjpowernode.crm.settings.mapper.DicValueMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:DicValueServiceImpl
 * Package:com.bjpowernode.crm.settings.service
 * Date:2022/6/6 19:54
 * Description:
 * Author:zsm@zhangshuming.com
 */

@Service
public class DicValueServiceImpl implements DicValueService {
    @Autowired
    private DicValueMapper dicValueMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<DicValue> queryAllDicValueList() {
        return dicValueMapper.selectAllDicValueList();

    }

    @Override
    public void saveCreateDicValue(DicValue dicValue) {
        dicValueMapper.insertSelective(dicValue);
    }

    @Override
    public DicValue queryAllDicValueById(String id) {
        return dicValueMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveEditDicValue(DicValue dicValue) {
        dicValueMapper.updateByPrimaryKeySelective(dicValue);
    }

    @Override
    public void deleteDicValueById(String[] ids) {
        dicValueMapper.deleteDicValueList(ids);
    }

    @Override
    public List<DicValue> queryDicValueListByTypeCode(String typeCode) {
        // 获取指定key的操作对象
        BoundListOperations boundListOperations = redisTemplate.boundListOps(typeCode);
        // 获取数据
        List<DicValue> dicValueList = boundListOperations.range(0, -1);
        // 判断是否有值
        if (ObjectUtil.isNull(dicValueList) || dicValueList.size() == 0){
            // 有直接返回
            // 没有去数据库查询
            dicValueList = dicValueMapper.selectDicValueListByTypeCode(typeCode);
            // 存放到redis缓存中
            dicValueList.forEach(c ->{
                boundListOperations.leftPush(c);
            });
            // 设置失效时间
            boundListOperations.expire(DateUtils.getRemainSecondsOneDay(new Date()), TimeUnit.SECONDS);
        }

        // 设置失效时间
        return dicValueList;
    }
}
